package com.example.app3_1;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

public class PermissionUtil {
    public static final int REQUEST_READ_MEDIA_PERMISSION = 1001;

    /**
     * 检查并请求读取图片所需的权限
     * @param activity
     * @return true 如果权限已被授予，false 如果需要请求权限
     */
    public static boolean checkAndRequestReadMediaPermission(Activity activity) {
        String[] requiredPermissions = getRequiredPermissions();
        List<String> permissionsToRequest = new ArrayList<>();

        // 检查每个权限是否已授予
        for (String permission : requiredPermissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

        if (permissionsToRequest.isEmpty()) {
            // 所有权限都已授予
            return true;
        } else {
            // 请求缺失的权限
            ActivityCompat.requestPermissions(activity, permissionsToRequest.toArray(new String[0]), REQUEST_READ_MEDIA_PERMISSION);
            return false;
        }
    }

    /**
     * 根据系统版本返回所需的权限
     * @return 所需的权限数组
     */
    public static String[] getRequiredPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33+
            return new String[]{"android.permission.READ_MEDIA_IMAGES"};
        } else {
            return new String[]{"android.permission.READ_EXTERNAL_STORAGE"};
        }
    }

    /**
     * 处理权限请求结果
     * @param grantResults 权限授予结果
     * @return true 如果所有需要的权限都被授予
     */
    public static boolean handlePermissionResult(int[] grantResults) {
        if (grantResults.length == 0) {
            return false;
        }
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}